package com.cblz.bd.server.core.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cblz.bd.common.core.entity.BaAttachment;
import com.cblz.bd.common.core.utils.ResultResponse;
import com.cblz.bd.common.core.utils.SearchParamsUtil;
import com.cblz.bd.server.core.annotation.AdminApiController;
import com.cblz.bd.server.core.annotation.Log;
import com.cblz.bd.server.core.entity.dto.BaAttachmentDTO;
import com.cblz.bd.server.core.entity.vo.BaAttachmentVO;
import com.cblz.bd.server.core.service.BaAttachmentService;
import io.vavr.Tuple3;
import io.vavr.Tuple5;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * {@code @Name:} BaAttachmentController
 * {@code @Description: }
 * {@code @Author:} by yanjieping
 * {@code @CreateDate:} 2022/11/23 - 周三
 */
@Slf4j
@RequiredArgsConstructor
@AdminApiController("routine.attachment")
public class BaAttachmentController {

    private final BaAttachmentService baAttachmentService;

    @PostMapping("index")
    public ResultResponse index(@RequestBody(required = false) Map<String, Object> searchParams) throws Exception {
        Tuple5 paramsHandle = SearchParamsUtil.searchParamsHandle2(searchParams);
        Tuple3<Page<BaAttachment>, QueryWrapper<BaAttachment>, BaAttachmentDTO> queryWrapper = SearchParamsUtil.params2QueryWrapper(new BaAttachment(), new BaAttachmentDTO(), paramsHandle);
        return new ResultResponse().data(baAttachmentService.index(queryWrapper));
    }

    @GetMapping("edit")
    public ResultResponse editBefore(@RequestParam Integer id) {
        BaAttachment baAttachment = baAttachmentService.getById(id);
        return new ResultResponse().data(BeanUtil.copyProperties(baAttachment, BaAttachmentVO.class).setSuffix(baAttachment.getName().substring(baAttachment.getName().lastIndexOf(".") + 1)));
    }

    @PostMapping("edit")
    @Transactional(rollbackFor = Exception.class)
    public ResultResponse edit(@RequestBody BaAttachment baAttachment) {
        Assert.notNull(baAttachment.getId());
        
        baAttachmentService.updateBaAttachment(baAttachment);
        return new ResultResponse().message("修改成功");
    }

    @DeleteMapping("del")
    @Log(description = "修改附件数据")
    @Transactional(rollbackFor = Exception.class)
    public void remove(@RequestBody Map ids) {
        baAttachmentService.removeByIds((List) ids.get("ids"));
    }
}
